package com.zegoto.design.design.behavior.iterator;


import java.util.Iterator;

// 聚合接口
interface Aggregate {
    MyIterator<String> createIterator();
}

// 具体聚合类
class Playlist implements Aggregate {
    private String[] songs;

    public Playlist(String[] songs) {
        this.songs = songs ;
    }

    public MyIterator<String> createIterator() {
        return new PlaylistIterator(songs);
    }
}

// 迭代器接口
interface MyIterator<T> {
    boolean hasNext();

    T next();
}

// 具体迭代器类
class PlaylistIterator implements MyIterator<String> {
    private String[] songs;
    private int position;

    public PlaylistIterator(String[] songs) {
        this.songs = songs;
        position = 0;
    }

    public boolean hasNext() {
        if (position < songs.length) {
            return true;
        } else {
            return false;
        }
    }

    public String next() {
        String song = songs[position];
        position++;
        return song;
    }
}

public class IteratorDemo {

    public static void main(String[] args) {
        Playlist playlist = new Playlist(new String[] {"Song A", "Song B", "Song C"});
        MyIterator<String> iterator = (MyIterator<String>) playlist.createIterator();

        while (iterator.hasNext()) {
            String song = iterator.next();
            System.out.println("Playing " + song);
        }
    }

}
